<?php
// +----------------------------------------------------------------------
// | 文件: index.php
// +----------------------------------------------------------------------
// | 功能: 提供todo api接口
// +----------------------------------------------------------------------
// | 时间: 2021-11-15 16:20
// +----------------------------------------------------------------------
// | 作者: rangangwei<gangweiran@tencent.com>
// +----------------------------------------------------------------------

namespace app\controller;

use Error;
use Exception;
use app\model\Counters;
use think\response\Html;
use think\response\Json;
use think\facade\Log;
use app\model\DelayHb;
use app\model\Bill;
use app\model\sendMsg;

class Index
{

    /**
     * 主页静态页面
     * @return Html
     */
    public function index(): Html
    {
//        $msg = new sendMsg;
//        $hassend = $msg
//            ->where('hassend', 1)
//            ->field('openid')->select();
//        $row = [];
//        foreach ($hassend as $send){
//            if(!in_array($send['openid'],$row)){
//                $row[] =  $send['openid'];
//            }
//        }
//        $json = file('./send202202011321.json');
//        foreach ($json as $k=>$js){
//            $openid = json_decode($js)->_openid;
//            $msg = new sendMsg;
//            $msg->create(
//                [
//                    'openid'=>$openid
//                ],
//                [
//                    'openid',
//                ],
//                true
//            );
//        }
//
//        exit;
        # html路径: ../view/index.html
        return response(file_get_contents(dirname(dirname(__FILE__)).'/view/index.html'));
    }


    public function getUser(): Json
    {
        $input = file_get_contents("php://input");
        $res = [];
        if ($temp_input = json_decode($input, true)) {
            $unionid = $temp_input['unionid'];
            $counters = new Counters;
            $res = $counters->where('unionId', $unionid)->find();
        }
        return json($res);
    }

    /**
     * 获取todo list
     * @return Json
     */
    public function getCount(): Json
    {
        try {
            $res = [];
            if($_SERVER['REQUEST_METHOD'] == 'POST') {
                $unionId = $_SERVER['HTTP_X_WX_UNIONID'];
                $openId = $_SERVER['HTTP_X_WX_OPENID'];
                $input = file_get_contents("php://input");
                if ($temp_input = json_decode($input, true)) {
                    $type = $temp_input['MsgType'];
                    if ($type == 'text' && $openId) {
                        $counters = new Counters;
                        $res = $counters->where('unionId', $unionId)->find();
                        if(!$res){
                            $dataRow = [
                                'openId' => $openId,
                                'unionId' => $unionId
                            ];
                            $counters = new Counters;
                            $counters->create(
                                $dataRow,
                                [
                                    'openId',
                                    'unionId',
                                ],
                                true
                            );
                            //search and sendHB
                            $hb = new DelayHb;
                            $hbResult = $hb
                                ->where('unionid', $unionId)
                                ->where('hassend', 0)
                                ->select();
                            $inHuoDongTime = time() < strtotime("2022-02-7");
                            if($hbResult && $inHuoDongTime){
                                foreach ($hbResult as $send){
                                    $this->sendHongBao($openId,$send);
                                    $hb->update([
                                        'hassend' => 1,
                                        'openid' => $openId,
                                        'sendtime' => date('Y-m-d H:i:s'),
                                        'id' => $send['id']
                                    ]);
                                }
                            }
                        }
                    }
                }
            }
            return json($res);
        } catch (Error $e) {
            $counters = new Counters;
            $counters->create(
                [
                    'res'=>json_encode($e->getMessage())
                ],
                [
                    'res',
                ],
                true
            );
        }
        return json($res);
    }


    /**
     * 根据id查询todo数据
     * @param $action `string` 类型，枚举值，等于 `"inc"` 时，表示计数加一；等于 `"reset"` 时，表示计数重置（清零）
     * @return Json
     */
    public function updateCount($action): Json
    {
        try {
            if ($action == "inc") {
                $data = (new Counters)->find(1);
                if ($data == null) {
                    $count = 1;
                }else {
                    $count = $data["count"] + 1;
                }

                $counters = new Counters;
                $counters->create(
                    ["count" => $count, 'id' => 1],
                    ["count", 'id'],
                    true
                );
            }else if ($action == "clear") {
                Counters::destroy(1);
                $count = 0;
            }

            $res = [
                "code" => 0,
                "data" =>  $count
            ];
            Log::write('updateCount rsp: '.json_encode($res));
            return json($res);
        } catch (Exception $e) {
            $res = [
                "code" => -1,
                "data" => [],
                "errorMsg" => ("更新计数异常" . $e->getMessage())
            ];
            Log::write('updateCount rsp: '.json_encode($res));
            return json($res);
        }
    }
    public function updateUser($data,$url){
        $data  = json_encode($data);
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        //        {"HTTP_CONNECTION":"keep-alive","HTTP_CONTENT_LENGTH":"175","HTTP_CONTENT_TYPE":"application\/json",
//            "HTTP_X_WX_UNIONID":"oOcKY6ODFmWmPDr9Irs8ezPbE12w",
//            "HTTP_X_WX_CLOUDBASE_ACCESS_TOKEN":"CLIBEoACiJrjSZ_xwCsYy9EHn-8Z0cTyqSus1JQvWapPwd2uyOoo-vAkd2EcbUSYwTKG-y8rrbxGwQnucXFaj1DSioWHMob4WBvFGjRvINznrTwPShbiX3KVQJfHUFS1V7C9sjOyXVW_e6CnyhoemfALpcrIUDYPmZ0tKRC_OkgreDChek6QM_k_R1i_JxV9BvnmEH9tLyO0qi4Grh9sjhTnN3097qRndUDjtIrLQ5HS2sNUkb9UQtbAqkVxr7yqEyU0ifVLoP1J3UC8a8R0QsFRXHwCDOk-d6fqECr9Mm4InSmYoHThZL78bISFhfjfzazCvmPU8c1YypUfcL6qr23CmbfMkhgFIAA",
//            "HTTP_X_WX_OPENID":"omnJQwph51NkUJNoFHq08zUzP5Dk",
//            "HTTP_X_WX_APPID":"wxcc7d452635a77e1d",
//            "HTTP_X_WX_REGION":"ap-shanghai",
//            "HTTP_X_WX_ENV":"prod-7gk427ez82db24c3",
//            "HTTP_HOST":"thinkphp-nginx-25l3-prod-7gk427ez82db24c3-1309418688.ap-shanghai.internal-run.tcloudbase.com",
//            "HTTP_X_WX_SERVICE":"thinkphp-nginx-25l3",
//            "HTTP_X_WX_SOURCE":"other",
//            "HTTP_ACCEPT":"*\/*",
//            "HTTP_X_CLOUDBASE_SESSIONTOKEN":"rjaj1o24NpbIcsRcZT19CdDIJgEiywda54f639cf6da815a89b58d2299b2ccd1cuductnsB4mDzC-DncliB_Md-utoiOFj5ZPQrpMX8GIDWAIDPHTthw2aT4-NfJwfPO65OyQnmrqfG_f0dy7_re5ZnqJXR2bEIZ6SA_D_DWn-pjv2hCnBY9u-xbaTh6WxXPwpUHch_MKklF_kiPvVaC3Lcng4XOpxe1ASBarvhhZn4hE1JTZx7JN0Ys7KdERoI3fOW-Bz7XWcoQCGLO4oW0BY0tHi-rpejhsBvstpmb-8SYuFWKB9EbbiC4DhSzeL7Cn8HZwclUy9tw4LoTeP4m7N1jt28bUb49md90pKhpW-8sQ4ILiPmEONFlm-zHUsm4uHqJgEqKi0LOzk77SmEeO5syRVe1OBVr7d78pMlupE",
//            "HTTP_X_CLOUDBASE_AUTHORIZATION":"1.0 TC3-HMAC-SHA256 Credential=AKIDOLvy-tuVE0jN3zhztLUng_tClznC9hXx-kXAs9ZH3Er-f684i21g7sIoppWrkuWV\/2022-01-25\/tcb\/tc3_request, SignedHeaders=content-type;host, Signature=903451c0bd8e4e4ae7f48ecc195a7102ebee52ca635d47e719a1af4e572aa4a1",
//            "HTTP_X_CLOUDBASE_TIMESTAMP":"1643102972",
//            "HTTP_X_CLOUDBASE_TRACE":"ZGEyZDFlNDU4NzQzNDljMWJmMmNlZWI0OGU1ZTcwOTgsODZhMTgwODZhYzM4N2VmOSxvbg==","HTTP_X_FORWARDED_PROTO":"http",
//            "HTTP_X_FORWARDED_HOST":"thinkphp-nginx-25l3-prod-7gk427ez82db24c3-1309418688.ap-shanghai.internal-run.tcloudbase.com",
//            "HTTP_USER_AGENT":"got (https:\/\/github.com\/sindresorhus\/got)"}
        return json_decode($output,true);
    }

    /**
     * @return Json
     */
    public function addDelayHb(): Json
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $input = file_get_contents("php://input");
            $amount = 30;
            if ($temp_input = json_decode($input, true)) {
                $day = date('j');
//                if($day > 0 && $day < 7){
                $unionid = $temp_input['unionid']??'';
                $str = $temp_input['str']??'';
                $hb_type = $temp_input['hb_type']??-1;
                $key = 'QWER-ABCD2022';

                $ssx = $temp_input['ssx']??'';
                if($ssx !== md5(md5($unionid.$hb_type.$str).$key)){
                    return json(['error']);
                }
                $hb = new DelayHb;
                $res = $hb
                    ->where('unionid', $unionid)
                    ->where('day', $day)
                    ->find();
                if(!$res){
                    switch ($hb_type){
                        case 0:
                            $amount = 88;
                            break;
                        case 1:
                            $amount = 188;
                            break;
                        case 2:
                            $amount = 388;
                            break;
                    }
                    $hbAdd = new DelayHb;
                    $hbAdd->create(
                        [
                            'unionid'=>$unionid,
                            'day'=>$day,
                            'amount'=>$amount,
                            'pin_order_no'=>mt_rand(1000000000,9999999999),
                        ],
                        [
                            'unionid',
                            'day',
                            'amount',
                            'pin_order_no',
                        ],
                        true
                    );
                }
//                }
            }
        }
        return json(['success']);
    }

    /**
     * @param $to_openid
     * @param $total_amount
     * @return Json
     */
    public function sendHongBao($to_openid,$info): Json
    {
        $act_name = '司米新春盲盒';
        $client_ip = '81.68.186.53';
        $mch_id = '1448601902';
        $mch_billno = $mch_id.date('Ymd').$info['pin_order_no'];
        $nonce_str = md5('mosaic2022');
        $re_openid = $to_openid;
        $remark = 'delayhb';
        $scene_id = 'PRODUCT_2';
        $send_name = '司米新春盲盒';
        $total_amount = $info['amount'];
//        $total_amount = 30;
        $total_num = 1;
        $wxappid = 'wxcc7d452635a77e1d';
        $wishing = '感谢您参加司米盲盒活动，祝您新春快乐！';
        $key = 'qpwoeirutyalskdjfhgzmxn123456789';
        $sign = $this->signEncry($act_name,$client_ip,$mch_billno,$mch_id,$nonce_str,$re_openid,$remark,$scene_id,$send_name,$total_amount,$total_num,$wishing,$wxappid,$key);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $xml =
            '<xml>' .
            '<act_name>' . $act_name . '</act_name>' .
            '<client_ip>' . $client_ip . '</client_ip>' .
            '<mch_billno>' . $mch_billno . '</mch_billno>' .
            '<mch_id>' . $mch_id . '</mch_id>' .
            '<nonce_str>' . $nonce_str . '</nonce_str>' .
            '<re_openid>' . $re_openid . '</re_openid>' .
            '<remark>' . $remark . '</remark>' .
            '<scene_id>' . $scene_id . '</scene_id>' .
            '<send_name>' . $send_name . '</send_name>' .
            '<total_amount>' . $total_amount . '</total_amount>' .
            '<total_num>' . $total_num . '</total_num>' .
            '<wishing>' . $wishing . '</wishing>' .
            '<wxappid>' . $wxappid . '</wxappid>' .
            '<sign>' . $sign . '</sign>' .
            '</xml>';
        try {
            $bill = new Bill;
            $bill->create(
                [
                    "delayhb_id" => $info['id'],
                    "openid" => $re_openid,
                    "day" => $info['day'],
                ],
                [
                    "delayhb_id",
                    "openid",
                    "day",
                ],
                true
            );
            $res = $this->sendRequest($xml,$url);
            $bill->where('delayhb_id',$info['id'])->update([
                'xml' => json_encode($res)
            ]);
        }catch (Exception $e){
//            $bill = new Bill;
//            $bill->create(
//                [
//                    "openid" => $re_openid,
//                    "day" => $info['day'],
//                    "xml" => $e->getMessage()
//                ],
//                [
//                    "openid",
//                    "day",
//                    "xml"
//                ],
//                true
//            );
            return json(['error']);
        }

        return json(['success']);
    }

    /**
     * @param $data
     * @param $url
     * @return array
     */
    public function sendRequest($data,$url): array
    {
        $headerArray = array(
            "Content-Type: application/xml",
            "Accept: application/xml",
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);

        curl_setopt($curl, CURLOPT_SSLCERTTYPE,'PEM');
        $real1 = realpath('/app/public/apiclient_cert.pem');
        $real2 = realpath('/app/public/apiclient_key.pem');
        curl_setopt($curl, CURLOPT_SSLCERT,$real1);

        curl_setopt($curl, CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($curl, CURLOPT_SSLKEY,$real2);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        libxml_disable_entity_loader(true);//curl返回的数据.在页面中展示是不会显示xml标签的.会将标签变成实体字符.这一行代表的是禁止变成实体字符
        $xml = \simplexml_load_string($output,'SimpleXMLElement', LIBXML_NOCDATA); //创建 SimpleXML对象
        $val = json_decode(json_encode($xml),true);//这样就变成数组了
        curl_close($curl);
        return $val;
    }

    /**
     * @param $act_name
     * @param $client_ip
     * @param $mch_billno
     * @param $mch_id
     * @param $nonce_str
     * @param $re_openid
     * @param $remark
     * @param $scene_id
     * @param $send_name
     * @param $total_amount
     * @param $total_num
     * @param $wishing
     * @param $wxappid
     * @param $key
     * @return string
     */
    public function signEncry($act_name,$client_ip,$mch_billno,$mch_id,$nonce_str,$re_openid,$remark,$scene_id,$send_name,$total_amount,$total_num,$wishing,$wxappid,$key): string
    {
        $stringSignTemp =
            'act_name=' .$act_name .
            '&client_ip=' .$client_ip .
            '&mch_billno=' .$mch_billno .
            '&mch_id=' .$mch_id .
            '&nonce_str=' .$nonce_str .
            '&re_openid=' .$re_openid .
            '&remark=' .$remark .
            '&scene_id=' .$scene_id .
            '&send_name=' .$send_name .
            '&total_amount=' .$total_amount .
            '&total_num=' .$total_num .
            '&wishing=' .$wishing .
            '&wxappid=' .$wxappid .
            '&key=' .$key;
        return strtoupper(md5($stringSignTemp));
    }

    /**
     * @param $data
     * @param $url
     * @return string
     */
    public function sendJsonRequest($data,$url): string
    {
        $headerArray = array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data)
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function sendToNoHbUser2(){
        $msg = new sendMsg;
        $hbResult = $msg
            ->where('hassend', 0)
            ->select();

        $msg = new sendMsg;
        $hassend = $msg
            ->where('hassend', 1)
            ->field('openid')->select();
        $row = [];
        foreach ($hassend as $send){
            if(!in_array($send['openid'],$row)){
                $row[] =  $send['openid'];
            }
        }


        foreach ($hbResult as $send){
            $msg = new sendMsg;
            if(in_array($send['openid'],$row)){
                $msg->update([
                    'hassend' => 2,
                    'id' => $send['id']
                ]);
            }else{
                $res = $this->sendMsg($send['openid']);
                $res = json_decode($res)->errcode;
                if($res == 0){
                    $msg->update([
                        'hassend' => 1,
                        'id' => $send['id']
                    ]);
                }else{
                    $msg->update([
                        'hassend' => $res,
                        'id' => $send['id']
                    ]);
                }
            }
        }
//        $msg2 = new Bill;
//        $hb2Result = $msg2
//            ->where('hassend_msg', 0)
//            ->select();
//        foreach ($hb2Result as $send2){
//            if(in_array($send2['openid'],$row)){
//                $msg2->update([
//                    'hassend_msg' => 2,
//                    'id' => $send2['id']
//                ]);
//            }else{
//                $res2 = $this->sendMsg($send2['openid']);
//                $res2 = json_decode($res2)->errcode;
//                if($res2 == 0){
//                    $msg2->update([
//                        'hassend_msg' => 1,
//                        'id' => $send2['id']
//                    ]);
//                }
//            }
//
//        }
    }

    public function sendToNoHbUser(){
        $msg = new sendMsg;
        $hbResult = $msg
            ->where('hassend', 0)
            ->select();

        $msg = new sendMsg;
        $hassend = $msg
            ->where('hassend', 1)
            ->field('openid')->select();
        $row = [];
        foreach ($hassend as $send){
            if(!in_array($send['openid'],$row)){
                $row[] =  $send['openid'];
            }
        }


//        foreach ($hbResult as $send){
//            $msg = new sendMsg;
//            if(in_array($send['openid'],$row)){
//                $msg->update([
//                    'hassend' => 2,
//                    'id' => $send['id']
//                ]);
//            }else{
//                $res = $this->sendMsg($send['openid']);
//                $res = json_decode($res)->errcode;
//                if($res == 0){
//                    $msg->update([
//                        'hassend' => 1,
//                        'id' => $send['id']
//                    ]);
//                }
//            }
//        }


        $msg2 = new Bill;
        $hb2Result = $msg2
            ->where('hassend_msg', 0)
            ->select();
        foreach ($hb2Result as $send2){
            if(in_array($send2['openid'],$row)){
                $msg2->update([
                    'hassend_msg' => 2,
                    'id' => $send2['id']
                ]);
            }else{
                $res2 = $this->sendMsg($send2['openid']);
                $res2 = json_decode($res2)->errcode;
                if($res2 == 0){
                    $msg2->update([
                        'hassend_msg' => 1,
                        'id' => $send2['id']
                    ]);
                }else{
                    $msg2->update([
                        'hassend_msg' => $res2,
                        'id' => $send2['id']
                    ]);
                }
            }
        }
    }
    public function sendMsg($openid){
        $token = '53_sg0xEWUyyP5zStmCdjYDpRXrCGpWNir2_hUId3S6TCm9ZqXE7mE956k2fIc7GgCZ1Px3Fxyh7g4OUlmHB66Q5ApCTr3yDUagYfVD9L45J1kC5JWJr7LkgVdt3_GLmvfgTixySQRk1MmvBBIeFIHhAHAORQ';
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
//        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send'.'?access_token='.$token;
        $data = [
            "touser"=> $openid,
            "msgtype"=> "text",
            "text"=>["content"=> "尊敬的用户：
感谢您参与“新春盲盒”活动，今日红包已被抢完，明天继续好运。司米祝您春节快乐！生活美满！"]

        ];
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $res = $this->sendJsonRequest($data,$url);
        return $res;
    }
}
